package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {
    private EmployeeMapper employeeMapper;

    @Autowired
    public void setEmployeeMapper(EmployeeMapper employeeMapper) {
        this.employeeMapper = employeeMapper;
    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Employee employee, Long[] ids) {
        employeeMapper.insert(employee);
        if (ids != null && ids.length > 0) {
            for (Long rid : ids) {
                employeeMapper.insertRelation(employee.getId(), rid);
            }
        }
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        //删除关系表
        employeeMapper.deleteRelation(employee.getId());
        if (ids != null && ids.length > 0) {
            for (Long rid : ids) {
                employeeMapper.insertRelation(employee.getId(), rid);
            }
        }
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo<>(employees);
    }

    @Override
    public Employee queryByUsernameAndPassword(Employee employee) {
        if (!StringUtils.hasLength(employee.getUsername())) {
            throw new LogicException("用户名为空");
        }
        if (!StringUtils.hasLength(employee.getPassword())) {
            throw new LogicException("密码为空");
        }
        Employee e = employeeMapper.queryByUsernameAndPassword(employee.getUsername(), employee.getPassword());
        if (e == null) {//如果无对象则账号密码错误
            throw new LogicException("用户名或者密码错误");
        }
        return e;
    }


    @Override
    public Employee queryByUsername(String username) {
        return employeeMapper.queryByUsername(username);
    }

    @Override
    public Workbook exportXls() {
        //查询所有员工数据
        List<Employee> employees = employeeMapper.selectAll();
        //创建工作薄excel
        Workbook workbook = new HSSFWorkbook();
        //创建工作表
        Sheet sheet = workbook.createSheet("通讯录");
        //创建标题行
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("用户名");
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("邮箱");
        row.createCell(3).setCellValue("年龄");
        for (int i = 0; i < employees.size(); i++) {
            //创建行
            row = sheet.createRow(i + 1);
            Employee employee = employees.get(i);
            //创建单元格
            row.createCell(0).setCellValue(employee.getUsername());
            row.createCell(1).setCellValue(employee.getName());
            row.createCell(2).setCellValue(employee.getEmail());
            if (employee.getAge() != null) {
                row.createCell(3).setCellValue(employee.getAge());
            }
        }
        return workbook;
    }

    /**
     * @param file
     * @throws Exception
     */
    @Override
    public void importXls(MultipartFile file) throws Exception {
        //读取上传的文件 , 并且封装为poi对象
        Workbook workbook = new HSSFWorkbook(file.getInputStream());
        //读取工作表
        Sheet sheet = workbook.getSheetAt(0);
        //读取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 0; i < lastRowNum; i++) {
            //读取行
            Row row = sheet.getRow(i + 1);
            Employee employee = new Employee();
            employee.setUsername(row.getCell(0).getStringCellValue());
            employee.setName(row.getCell(1).getStringCellValue());
            employee.setEmail(row.getCell(2).getStringCellValue());
            employee.setAge((int) row.getCell(3).getNumericCellValue());
            employee.setPassword("12321");
            employeeMapper.insert(employee);
        }
    }

    @Override
    public Employee queryPasswordById(Long id, String oldPassword) {
        Employee employee = employeeMapper.queryPasswordById(id);
        if (!(employee.getPassword().equals(oldPassword))) {
            //密码不同报错
            throw new RuntimeException("原密码错误");
        }
        return employee;
    }

    @Override
    public void updatePassword(Long id, String newPassword) {
        if (UserContext.getCurrentUser().getPassword().equals(newPassword)) {
            throw new RuntimeException("新密码和原密码相同");
        }
        employeeMapper.updatePassword(id, newPassword);
    }

    @Override
    public Employee queryPassword(String oldPassword) {
        Employee employee = UserContext.getCurrentUser();
        if (!(employee.getPassword().equals(oldPassword))) {
            throw new RuntimeException("原密码错误");
        }
        return employee;
    }

    @Override
    public void updatePasswordById(Long id) {
        employeeMapper.updatePasswordById(id, "123");
    }

    @Override
    public Employee updatePassword2(String oldPassword, String newPassword) {
        //Employee employee = employeeMapper.queryPasswordById(UserContext.getCurrentUser().getId());
        Employee employee = UserContext.getCurrentUser();
        if (!(employee.getPassword().contains(oldPassword))) {
            throw new LogicException("原密码错误");
        }
        employeeMapper.updatePassword(employee.getId(), newPassword);
        return employee;
    }

    @Override
    public void EmpDisableOrRecovery(Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        boolean status = employee.isStatus();
        //employee.setStatus(!status);
        employeeMapper.updateStatusById(id, !status);
    }

    @Override
    public boolean queryStatusByUsername(String username) {
        boolean status = employeeMapper.queryStatusByUsername(username);
        if (!status) {
            throw new LogicException("1");
        }
        return status;
    }

}
